import { observable, useStrict, action, runInAction } from 'mobx'
import { getUser, getMenu, getHelp } from '../api/datasource'
import {apiUrl} from '../api/constant'
import {fetchData} from '../api/datasource'
import { message } from 'antd'

useStrict(true)

const urlConfig = {
    getMenu: '/user/getMenu',
    getHelp: '/role/getModuleList'
}

//国际化配置
const localeData = [
    {
        key: 'en',
        name: '中文'
    },
    {
        key: 'zh',
        name: 'EN'
    },
]

class State {
    @observable collapse = false
    @observable userCityList = []
    @observable shopId = undefined
    @observable menu = []
    @observable helpMessage = ''
    @observable helpLoading = false

    @action changeCollapse = () => {
        this.collapse = !this.collapse
    }

    //get user info
    @observable baseUser = {
        username: ''
    }

    @action getUserInfo = async (user) => {
        let res = await getUser(user)
        runInAction("update state after fetching data", () => {
            this.baseUser = res.data.data
            if(res.data.data) {
                this.userCityList = res.data.data.cityList || []
            }
        })
    }

    @action changeShopId = (shopId) =>{
        this.shopId = shopId
    }

    //locale 国际化, 默认中文
    @observable locale = localeData[1]
    @action changeLocale = (key) => {
        localeData.forEach(item => {
            if (item.key !== key) {
                this.locale = item
            }
        })
    }

    @action('获取用户菜单') getMenu = async (userName) => {
        const data = encodeURI(JSON.stringify({userName}))
        try {
            const result = await fetchData(urlConfig.getMenu, 'get', data )
            runInAction(() => {
                if(result.data.data) {
                    this.menu = result.data.data
                } else {
                    this.menu = []
                }
            })
        } catch (e) {
            message.error('菜单获取失败')
            runInAction(() => {
                this.menu = []
            })
        }
    }

    @action('清空用户菜单') initMenu = () => {
        this.menu = []
    }

    @action('获取帮助信息') getHelp = async (moduleId) => {
        this.helpLoading = true
        const data = encodeURI(JSON.stringify({moduleId}))
        try {
            const result = await fetchData(urlConfig.getHelp, 'get', data )
            runInAction(() => {
                this.helpLoading = false
                if (result.data.moduleList && result.data.moduleList[0]) {
                    this.helpMessage = result.data.moduleList[0].messages
                } else {
                    this.helpMessage = ''
                }
            })
        } catch (e) {
            message.error('获取帮助信息失败')
            runInAction(() => {
                this.helpLoading = false
                this.helpMessage = ''
            })
        }
    }

    @action('清除帮助信息') clearHelp = () => {
        this.helpMessage = ''
    }
}

export default new State()